<template>
  <div class="product-choose">
    <div
      v-if="!relativeType"
      class="handel-header">
      <el-popover
        v-model="showPopover"
        placement="right-start"
        width="700"
        popper-class="no-padding-popover"
        trigger="click">

        <relative-card
          v-model="showPopover"
          :request-config="requestConfig"
          :default-value="productList"
          primary-key="productId"
          label="选择产品"
          @close="showPopover = !showPopover"
          @confirm="handleRelativeConfirm" />

        <el-button
          slot="reference"
          type="primary"
          size="mini"
          class="xr-btn--primary">
          添加产品
        </el-button>
      </el-popover>
    </div>

    <el-table
      :data="productList"
      style="width: 100%;">
      <template v-for="(field, index) in fieldList">
        <el-table-column
          :key="index"
          :prop="field.prop"
          :label="field.label"
          show-overflow-tooltip />
      </template>
      <el-table-column label="入库数量">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.num"
            :controls="false"
            :precision="2"
            :min="0"
            :max="relativeType ? scope.row.weiNumber : Number.POSITIVE_INFINITY"
            placeholder="请输入"
            @change="totalPriceChange" />
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.remarks"
            :maxlength="100"
            placeholder="请输入"
            @change="totalPriceChange" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click.stop="removeItem(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
/**
 * Create by yxk at 2020/6/10
 */
import { jxcFieldQueryListHeadAPI, jxcFieldQueryPageListAPI } from '@/api/jxc/field'
import { jxcReceiptQueryEdProductListAPI } from '@/api/jxc/receipt'

import RelativeCard from '../../RelativeCard'
import JxcTypes from '../../../jxcTypes'
import { objDeepCopy } from '@/utils'

export default {
  name: 'ReceiptChoose',
  components: {
    RelativeCard
  },
  props: {
    id: {
      type: [String, Number]
    },
    relativeType: {
      type: String,
      default: null
    },
    defaultValue: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      showPopover: false,

      fieldList: [],
      productList: [],
      totalPrice: 0,
      totalCount: 0
    }
  },
  computed: {
    requestConfig() {
      return {
        fieldRequest: jxcFieldQueryListHeadAPI,
        fieldParams: {
          label: JxcTypes.jxc_product.label
        },
        listRequest: jxcFieldQueryPageListAPI,
        listParams: {
          label: JxcTypes.jxc_product.label,
          searchList: [{
            formType: 'text',
            type: 1,
            name: 'product_ishelf', // 上架的产品
            values: [1]
          }]
        },
        placeholder: '请输入产品名称',
        searchParamsFn: (params, keyword) => {
          if (keyword) {
            params.searchList.push({
              name: 'product_name',
              formType: 'text',
              type: 3,
              values: [keyword]
            })
          }
          return params
        }
      }
    }
  },
  watch: {
    defaultValue: {
      handler(val) {
        if (val.length > 0) {
          this.productList = objDeepCopy(val)
        }
      },
      deep: true,
      immediate: true
    },
    relativeType: {
      handler(val) {
        this.productList = []
        if (!val) {
          this.fieldList = [
            { label: '产品名称', prop: 'productName', width: null },
            { label: '产品规格', prop: 'spDataValue', width: null },
            { label: '产品单位', prop: 'productCompany', width: null }
          ]
        } else {
          this.fieldList = [
            { label: '产品名称', prop: 'productName', width: null },
            { label: '产品规格', prop: 'spDataValue', width: null },
            { label: '产品单位', prop: 'productCompany', width: null },
            { label: '未入库数量', prop: 'weiNumber', width: null }
          ]
          this.getProductList()
        }
      },
      immediate: true
    },
    id: {
      handler(val) {
        this.productList = []
        if (!val) return
        this.getProductList()
      },
      immediate: true
    }
  },
  methods: {
    getProductList() {
      if (!this.id || !this.relativeType) return
      jxcReceiptQueryEdProductListAPI({
        orderId: this.id,
        receiptType: this.relativeType === 'purchase_cause' ? '采购入库' : '销售退货入库'
      }).then(res => {
        console.log('res: ', res.data)
        this.productList = res.data.map(o => {
          return {
            ...o,
            num: o.weiNumber,
            remarks: ''
          }
        })
        this.totalPriceChange()
      }).catch(() => {
        this.productList = []
      })
    },

    handleRelativeConfirm(data) {
      // console.log('data', data)
      // console.log('productList', this.productList)
      const dataIds = data.valData
      // 去掉被删除的产品
      const productList = this.productList.filter(o => dataIds.includes(o.productId))
      // 过滤掉已经添加过的产品
      const ids = this.productList.map(o => o.productId)
      const list = data.data.filter(o => !ids.includes(o.productId)).map(o => {
        return {
          productCode: o.productCode,
          productCompany: o.productCompany,
          productId: o.productId,
          productName: o.productName,
          purchasesNumber: 0,
          receiptNumber: 0,
          spDataValue: o.spDataValue,
          weiNumber: 0,
          num: 0,
          remarks: '',
          relationId: ''
        }
      })
      this.productList = [...productList, ...list]
      this.showPopover = false
      this.totalPriceChange()
    },

    removeItem(index) {
      this.productList.splice(index, 1)
      this.totalPriceChange()
    },

    totalPriceChange() {
      this.$emit('change', {
        data: this.productList,
        total: 0
      })
    }
  }
}
</script>

<style scoped lang="scss">
  @import "index";
</style>
